package it.polimi.swKnights.SWIMv2.ejb.registration;

import it.polimi.swKnights.SWIMv2.ejb.entityBeans.RegisteredUser;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.ToConfirmUser;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.AlreadyExistingException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidConfirmationCodeException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.NotRegisteredConfirmException;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class UserConfirmationHandlerBean
 */
@Stateless
public class UserConfirmationHandler implements UserConfirmationHandlerRemote
{

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager manager; // manager handlin the persistence data

	@Override
	public void confirmUser(String userName, String registrationCode)
			throws InvalidConfirmationCodeException,
			NotRegisteredConfirmException, AlreadyExistingException
	{

		ToConfirmUser user = this.manager.find(ToConfirmUser.class, userName);

		/* if no user found or confirmation- */
		if (user != null)
		{
			if (!user.getActivationCode().equals(registrationCode))
			{
				/* -code is wrong - */
				throw new InvalidConfirmationCodeException();
			}
			else
			{
				// remove user from ToConfirmUser
				// write user into Registered user

				RegisteredUser registeredUser = new RegisteredUser(
						user.getUserName(), user.getPasswordHash(),
						user.geteMail());

				registeredUser.setBirthday(user.getBirthday());
				registeredUser.setName(user.getName());
				registeredUser.setSex(user.getSex());
				registeredUser.setSurname(user.getSurname());
				registeredUser.setAddress(user.getAddress());

				manager.remove(user);
				manager.persist(registeredUser);

			}
		}
		else
		{
			this.handleErrors(userName);
		}

	}

	private void handleErrors(String userName) throws AlreadyExistingException,
			NotRegisteredConfirmException
	{
		try
		{
			this.manager.getReference(RegisteredUser.class, userName);
			throw new AlreadyExistingException("User already confirmed");
		}
		catch (EntityNotFoundException e)
		{
			throw new NotRegisteredConfirmException();
		}
	}

}
